// script.js
let that=this;
document.addEventListener('DOMContentLoaded', async function() {
    const wordslist=["11-19.txt"];
    let words = ["example", "rhetorical", "immaculate"]; // 假设这是从文件读取的单词列表
    words=await that.readFileIntoArray("11-19.txt");
    let currentIndex = 0;

    function loadWord(index) {
        const word = document.getElementById('word');
        const audioPlayer = document.getElementById('audio-player');
        const translation = document.getElementById('translation');

        word.textContent = words[index];
        
        // 调用API获取发音和翻译
        fetchAudioAndTranslation(words[index], (audioSrc, translated) => {
            audioPlayer.src = audioSrc;
            //translation.textContent = translatedText;
            // 获取HTML容器元素
            // 将JSON对象转换为HTML并显示
            jsonToHtml(translated, translation);

        });
    }

    function fetchAudioAndTranslation(word, callback) {
        // 假设这是API的URL
        const apiUrl = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
        
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                console.log(data);
                //const audioSrc = data.audioSrc; // 假设API返回音频源
                callback(data[0].phonetics[0].audio, data[0].meanings);
            })
            .catch(error => console.error('Error fetching data:', error));
    }

    document.getElementById('next').addEventListener('click', () => {
        currentIndex = (currentIndex + 1) % words.length;
        loadWord(currentIndex);
    });

    document.getElementById('prev').addEventListener('click', () => {
        currentIndex = (currentIndex - 1 + words.length) % words.length;
        loadWord(currentIndex);
    });

    // 初始化加载第一个单词
    loadWord(currentIndex);
});


// json-to-html.js
function jsonToHtml(json, parentElement) {
    parentElement.innerHTML="";
    for (const key in json) {
        if (json.hasOwnProperty(key)) {
            const value = json[key];
            const element = document.createElement('div');
            element.textContent = key + ': ' + value;
            parentElement.appendChild(element);

            // 如果值是对象或数组，递归调用
            if (typeof value === 'object' && value !== null) {
                jsonToHtml(value, element);
            }
        }
    }
}

// 示例JSON对象
const json = {
    name: "John",
    age: 30,
    married: true,
    children: ["Alice", "Bob"],
    address: {
        street: "123 Main St",
        city: "Anytown",
        state: "CA",
        zip: "12345"
    }
};


async function readFileIntoArray(filename) {
    try {
        // 使用fetch API获取文件
        const response = await fetch(filename);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        // 读取文件内容为文本
        const text = await response.text();
        // 将文件内容按行分割，存储到数组中
        const lines = text.split('\r\n');
        // 现在lines数组包含了文件的每一行
        
        return lines;
    } catch (error) {
        console.error('Could not read the file:', error);
    }
}

// 调用函数
// readFileIntoArray("11-19.txt").then(lines => {
//     // 这里可以处理读取到的数组
//     console.log(lines);
// });
